package tree.test116;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/17 9:31
 */
public class Solution1 {

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        if (root == null || root.left == null) return root;
        Node cur = root;
        Node start = cur;
        Node pre;
        while (true) {
            if (cur != null) {
                if (cur.left != null) {
                    cur.left.next = cur.right;
                    pre = cur;
                    cur = cur.next;
                    if (cur != null) {
                        pre.right.next = cur.left;
                    }
                } else {
                    break;
                }
            } else {
                cur = start.left;
                start = cur;
            }
        }
        return root;
    }
}
